/*
 * @Author: zhanghong
 * @Date: 2019-01-17 20:20:01
 * @Description: 图片处理工具函数
 */
// import isSupportWebp from './webp'
import { network } from './constants'

// some small (2x1 px) test images for each feature
const images = {
	basic:
		'',
	lossless:
		''
}

function isSupportWebp(feature) {
	try {
		return new Promise((resolve, reject) => {
			const img = new Image()
			img.onload = function() {
				if (this.width === 2 && this.height === 1) {
					resolve(true)
				} else {
					reject(false)
				}
			}
			img.onerror = function() {
				reject(false)
			}
			img.src = images[feature || 'basic']
		})
	} catch (error) {
		console.log('error', error)
	}
}

const _imageQuality = (function() {
	let q = '70'
	if (network !== 'unknown') {
		switch (network) {
			case 'wifi':
			case '4g':
				q = '70'
				break
			case '3g':
				q = '50'
				break
			case '2g':
				q = '20'
				break
			default:
				q = '60'
				break
		}
	}
	return q
})()

let supportWebp = false
isSupportWebp().then(() => {
	supportWebp = true
})

/**
 * 移除url中的协议部分
 * @param {string} url - 带协议的url
 * @returns {*}
 */
export function removeProtocol(url) {
	if (url.match(/^http:|^https:/i) !== null) {
		url = url.replace(/^http:|^https:/i, '')
	}
	return url
}
// 短链默认 210x210 长链 会设置指定 size
export function formatImageUrl(url, size) {
	if (!url) {
		return ''
	}
	url = removeProtocol(url)

	//如果支持webp就用webp，否则用jpg
	let extension = supportWebp ? 'webp' : 'jpg'

	// 如果原图是png,扩展名就用png
	const originalPNG = /(\w+\.png!q\d+\.(png|jpg|gif))/
	if (url.match(originalPNG)) extension = 'png'

	const quality = _imageQuality
	const extensionArray = ['png', 'jpg', 'webp']

	if (extensionArray.indexOf(extension) === -1) {
		console.warn('wrong extension')
		return
	}

	const i = url.indexOf('!q')
	if (i !== -1) {
		url = url.substring(0, i)
	}

	if (url.match(/^\/\//) !== null) {
		url = url + '!q' + quality + '.' + extension
		// console.log(size)
		if (size) url = ImgUrlSetSize(url, size)
	} else {
		size = size || '210x210'
		// 防止带上size 的图片多加一次size
		url = ImgUrlRemoveSize(url)
		url =
			'//m.360buyimg.com/n1/s' +
			size +
			'_' +
			url +
			'!q' +
			quality +
			'.' +
			extension
	}

	return url
}

export function ImgUrlRemoveSize(url) {
	const newUrl = url.replace(/s[0-9]{1,4}x[0-9]{1,4}_/g, '')
	return newUrl
}

export function ImgUrlSetSize(url, size) {
	if (!url) {
		return ''
	}
	url = ImgUrlRemoveSize(url)
	if (!size) {
		return url
	}
	const pattern = 's' + size + '_jfs'
	const newUrl = url.replace(/jfs/g, pattern)
	return newUrl
}
